package com.ypj.indusynergyems.common.biz.user;

import com.ypj.indusynergyems.dao.entity.MenuEntity;
import com.ypj.indusynergyems.toolkit.MenuUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * 三级菜单权限的拦截器
 */
@Component
@Slf4j
public class SystemAuthorityInterceptor implements HandlerInterceptor {

    //访问目标方法之前执行
    //拦截器的核心逻辑
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、判断是否为ajax请求，是--放行  不是--执行2步操作
        if (!isAjax(request)){
            //2、获取访问的url
            String requestURI = request.getRequestURI();
            log.info("拦截器中的请求路径，requestURI={}",requestURI);
            //3、从session中获取menuList(登录用户可以操作的所有菜单列表)、userSecondMenus列表
            HttpSession session = request.getSession();  //获取session对象，通过请求对象中的getSession()方法
            List<MenuEntity> menuList = (List<MenuEntity>) session.getAttribute("menuList");
            List<MenuEntity> userSecondMenus = (List<MenuEntity>) session.getAttribute("secondMenus");
            //4、获取三级菜单并且保存到请求属性（request、model）
            Integer menuId =  MenuUtils.getMenuIdByUrl(requestURI,userSecondMenus);  //根据访问的url获取对应的菜单id
            List<MenuEntity> userThirdMenus =  MenuUtils.getChild(menuId,menuList);  //获取访问的菜单id对应的所有子菜单(三级菜单)
            request.setAttribute("userThirdMenus",userThirdMenus);
        }
        return true;
    }

    //判断请求是否为ajax请求
    public  boolean isAjax(HttpServletRequest request){
        String header = request.getHeader("X-Requested-With");  //获取请求头中X-Requested-With的属性值
        if ("XMLHttpRequest".equals(header)){
            return  true;   //是ajax请求
        }
        return false;  //不是ajax请求
    }

    //执行目标方法之后，渲染视图之前执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //执行方法并渲染视图完成之后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

